'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searchControllersFile() {
    let file = fs.readdirSync(__dirname);
    let controllers = file.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });
    return controllers;
}

function registerControllersFile(files) {
    files.forEach(item => {
        let resultPath = path.join(__dirname,item);
        let routerObj = require(resultPath);
        for(let key in routerObj){
            let type = routerObj[key][0];
            let fn = routerObj[key][1];
            if(type === 'get'){
                router.get(key,fn)
            }else{
                router.post(key,fn)
            }
        }
    })
}

module.exports = (dir) => {
    let defaultDir = dir || '/controllers';

    let pointPath = path.join(__dirname,defaultDir);

    let files = searchControllersFile(pointPath);

    registerControllersFile(files);

    return router.routes();
}